package spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.executor;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import spring.cloud.tasks.common.curator.Curator;
import spring.cloud.tasks.common.task_item_allot.Executor;
import spring.cloud.tasks.common.task_item_allot.TaskItem;
import spring.cloud.tasks.tasks_manager.task_item_assign.PreferExecutorSettings;
import spring.cloud.tasks.tasks_manager.task_item_assign.TaskItemAssignUtils;
import spring.cloud.tasks.tasks_manager.task_item_assign.pick_up.PickUp;

import java.util.ArrayList;
import java.util.List;

/**
 * executor上线，仅仅添加executor空壳，如果其不存在；如果已经存在，重新设置下ip，防止ExecuteJobServerOnlineShardingTask先于执行而没设ip
 * <p>
 * 特别的，如果当前没有executor，也就是这是第一台executor上线，则需要域全量分片，因为可能已经有任务处于启用状态了。
 */
@Slf4j
@Setter
@Getter
public class PickUpWhenExecutorOnline extends PickUp {

    private String executorId;

    private String ip;


    @Override
    protected void log() {
        log.info("Execute the {} with {} online", this.getClass().getSimpleName(), executorId);
    }

    @Override
    public boolean pickUp(Curator curator,//
                          List<String> taskIdList,//
                          List<String> enableTaskIdList,//
                          List<TaskItem> pickUpEdTaskItemList,//
                          List<TaskItem> discardTaskItemList,//
                          List<Executor> onlineExecutorList,//
                          List<Executor> ownTrafficOnlineExecutorList,//
                          PreferExecutorSettings preferExecutorSettings) throws Exception {
        // 如果没有Executor在运行，则需要进行全量分片
        if (onlineExecutorList.isEmpty()) {
            log.warn("There are no running executors, need all sharding");
            //taskItemAssignService.setNeedTaskItemReAssign(true);

            return false;
        }

        Executor targetOnlineExecutor = null;
        for (int i = 0; i < onlineExecutorList.size(); i++) {
            Executor onlineExecutor = onlineExecutorList.get(i);
            if (onlineExecutor.getExecutorId().equals(executorId)) {
                targetOnlineExecutor = onlineExecutor;
                break;
            }
        }
        if (targetOnlineExecutor == null) {
            targetOnlineExecutor = new Executor();
            targetOnlineExecutor.setExecutorId(executorId);
            targetOnlineExecutor.setIp(ip);
            targetOnlineExecutor.setNotFlowControl(TaskItemAssignUtils.executorIsNotFlowControl(curator, executorId));
            targetOnlineExecutor.setTaskIdList(new ArrayList<String>());
            targetOnlineExecutor.setTaskItemList(new ArrayList<TaskItem>());
            onlineExecutorList.add(targetOnlineExecutor);
            if (targetOnlineExecutor.isNotFlowControl()) {
                ownTrafficOnlineExecutorList.add(targetOnlineExecutor);
            }
        } else { // 重新设置下ip
            targetOnlineExecutor.setIp(ip);
        }

        return true;
    }


}
